﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using WeiBeeCommon.DataTypes;
using System.Diagnostics;
using WeiBeeCommon.Core;

namespace FollowersToExcel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            _bgwAnalisys.WorkerReportsProgress = true;
            _bgwAnalisys.DoWork += new DoWorkEventHandler(_bgwAnalisys_DoWork);
            _bgwAnalisys.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bgwAnalisys_RunWorkerCompleted);
            _bgwAnalisys.ProgressChanged += new ProgressChangedEventHandler(_bgwAnalisys_ProgressChanged);            
        }

        private readonly BackgroundWorker _bgwAnalisys = new BackgroundWorker();

        void _bgwAnalisys_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            string progressString = e.UserState as string;
            tbResult.Text += progressString;
        }

        void _bgwAnalisys_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tbResult.Text += @"完成读取" + Environment.NewLine;
            btnSave.Enabled = true;
        }

        void _bgwAnalisys_DoWork(object sender, DoWorkEventArgs e)
        {
            AnalisysSina();
        }

        private void AnalisysSina()
        {
            string progressString = @"开始读取粉丝列表(最多只能读取5000个)..." + Environment.NewLine;
            _bgwAnalisys.ReportProgress(0, (object)progressString);
            var weibee = new WeiBeeCommon.Core.WeiBeeSina();
            weibee.OAuth = new WeiBeeCommon.Core.OAuthSina();
            weibee.OAuth.ConsumerKey = "1758087936";
            weibee.OAuth.ConsumerSecret = "bed16662269e81094dff3bfbe70af158";
            weibee.OAuth.Token = "8ff27aad039c9ca142dce3b66b8f38bf";
            weibee.OAuth.TokenSecret = "b91129b04eb5bb0a79390ff574a81d1d";

            var usrinfo_preread = GetUserInfoFromUrl(tbUserUrl.Text);
            usrinfo = weibee.ShowUser(usrinfo_preread.id);
            _bgwAnalisys.ReportProgress(1, (object)usrinfo.id);

            string firstpage = weibee.Followers(usrinfo.id, 200);
            followers = weibee.FollowersOnList(firstpage);
            string counter = string.Format(Environment.NewLine + ">>>读取了{0}个粉丝信息." + Environment.NewLine, followers.Count);
            _bgwAnalisys.ReportProgress(3, (object)counter);
            int cursorvalue = weibee.GetNextCursor(firstpage);
            string cursorinfo = string.Format(">>>从{0}继续读取..." + Environment.NewLine, cursorvalue);
            _bgwAnalisys.ReportProgress(4, (object)cursorinfo);
            while (cursorvalue != 0)
            {
                string currentpage = weibee.Followers(usrinfo.id, 200, cursorvalue);
                var currentfollowers = weibee.FollowersOnList(currentpage);
                _bgwAnalisys.ReportProgress(4,
                    (object)string.Format(">>>读取了{0}个粉丝信息." + Environment.NewLine, currentfollowers.Count));
                followers.AddRange(currentfollowers);
                cursorvalue = weibee.GetNextCursor(currentpage);
                cursorinfo = string.Format(">>>从{0}继续读取..." + Environment.NewLine, cursorvalue);
                _bgwAnalisys.ReportProgress(4, (object)cursorinfo);
            }
        }

        private void btnAnalisys_Click(object sender, EventArgs e)
        {
            tbResult.Text = string.Empty;
            btnSave.Enabled = false;
            _bgwAnalisys.RunWorkerAsync();
        }

        private SinaUser usrinfo;
        private List<WeiBeeCommon.DataTypes.SinaUser> followers;
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (followers == null || followers.Count == 0) return;
            string filename = string.Format("{0}.csv",usrinfo.name);
            using (var sw = new StreamWriter(filename,false, Encoding.UTF8))
            {
                sw.WriteLine(WeiBeeCommon.Core.WeiBeeSina.OneLineHeader);
                foreach (var usr in followers)
                {
                    sw.WriteLine(WeiBeeCommon.Core.WeiBeeSina.GetSinaUserInOneLine(usr));
                }
            }
            MessageBox.Show(string.Format(@"成功保存粉丝列表:{0}", filename));
        }
        public SinaUser GetUserInfoFromUrl(string url)
        {
            var wc = new WebClient();
            var userpagestring = wc.DownloadString(url);
            Regex reg = new Regex(@"http://weibo.com/(\d+)");
            var matches = reg.Matches(userpagestring);
            if (matches.Count == 0)
            {
                Regex corpreg = new Regex(@"http://a.weibo.com/profile.php\?uid\=(\d+)");
                matches = corpreg.Matches(userpagestring);
            }
            var result = new WeiBeeCommon.DataTypes.SinaUser();
            result.id = matches[0].Groups[1].Value;
            return result;
        }

        public WeiBeeType GetWeiBeeType(string url)
        {
            WeiBeeType result = WeiBeeType.None;
            var sinaRegex = new Regex("weibo.com");
            var sohuRegex = new Regex("t.sohu.com");
            if (sinaRegex.IsMatch(url)) result = WeiBeeType.Sina;
            if (sohuRegex.IsMatch(url)) result = WeiBeeType.Sohu;
            return result;
        }

        private void btnFileLocation_Click(object sender, EventArgs e)
        {
            var proc = new Process();
            proc.StartInfo.FileName = "explorer.exe";
            proc.StartInfo.Arguments = AppDomain.CurrentDomain.BaseDirectory;
            proc.Start();
        }

        private void tbUserUrl_TextChanged(object sender, EventArgs e)
        {
            Dictionary<WeiBeeType, string> weibeeNameDict = new Dictionary<WeiBeeType, string>
            {
                {WeiBeeType.Sohu,"搜狐"},
                {WeiBeeType.Sina,"新浪"},
                {WeiBeeType.QQ,  "腾讯"},
                {WeiBeeType.None,"未知"}
            };
            this.label1.Text = weibeeNameDict[GetWeiBeeType(tbUserUrl.Text)];
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tbUserUrl_TextChanged(sender, e);
        }
    }
}
